const Service = require('egg').Service;
const _ = require('lodash');

let User, Project, UserProject;

class ProjectService extends Service {
    // 默认不需要提供构造函数。
    constructor(ctx) {
        super(ctx);
        /*    如果需要在构造函数做一些处理，一定要有这句话，才能保证后面 `this.ctx`的使用。
            就可以直接通过 this.ctx 获取 ctx 了
            还可以直接通过 this.app 获取 app 了*/
        User = this.app.model.User;
        Project = this.app.model.Project;
        UserProject = this.app.model.UserProject;
    }

    /**用户在项目里的角色
     * -1 与项目没有关系
     * 0 管理员
     * 1 项目负责人
     * 2 项目执行人
     * */
    async userRole(project_id, user_id) {
        let role = -1;

        if (this.ctx.user.level.id <= 2) {
            role = 0;
        } else {
            const level = await this.app.model.UserProject.findOne({where: {user_id, project_id}});
            if (level)
                role = level.type;
        }
        return role;
    }

    //增加项目管理员
    async addManager(project, user) {
        await UserProject.destroy({where: {user_id: user.id, project_id: project.id}});
        await UserProject.create({user_id: user.id, project_id: project.id, type: 0});
        await this.checkUserLevel(user);
    }

    //增加项目执行员
    async addMember(project, user) {
        await UserProject.destroy({where: {user_id: user.id, project_id: project.id}});
        await UserProject.create({user_id: user.id, project_id: project.id, type: 1});
        await this.checkUserLevel(user);
    }

    //移除项目管理员
    async removeManager(project, user) {
        await UserProject.destroy({where: {user_id: user.id, project_id: project.id, type: 0}});
        await this.checkUserLevel(user);
    }

    //移除项目执行员
    async removeMember(project, user) {
        await UserProject.destroy({where: {user_id: user.id, project_id: project.id, type: 1}});
        await this.checkUserLevel(user);
    }

    //重新计算用户级别
    async checkUserLevel(user) {
        const all = await UserProject.findAll({where: {user_id: user.id}});
        //用户没有任何项目关系
        let level_id = this.app.userDefaultLevel;
        //有项目负责人关系
        if (!_.isEmpty(_.find(all, {type: 0}))) {
            level_id = 3;
        } else if (!_.isEmpty(_.find(all, {type: 1}))) {
            level_id = 4;
        }
        await this.app.model.User.update({level_id},{where: {id: user.id}});
    }
}

module.exports = ProjectService;